# .zshrc
# ======
#
# zshrc is sourced for "interactive" shells (either non-login or login)
# vim: set sts=2 sw=2 ts=2

#   ~/.zshenv -> ~/.zprofile -> [/etc/zshrc] -> ~/.zshrc -> ~/.zlogin
#                                               ^^^^^^^^
#
# See [fighting with path_helper] https://gist.github.com/Linerre/f11ad4a6a934dcf01ee8415c9457e7b2
# See https://github.com/rbenv/rbenv/wiki/Unix-shell-initialization
# See https://unix.stackexchange.com/questions/71253/what-should-shouldnt-go-in-zshenv-zshrc-zlogin-zprofile-zlogout
# See https://medium.com/@rajsek/zsh-bash-startup-files-loading-order-bashrc-zshrc-etc-e30045652f2e

# Note that we have unsetopt GLOBAL_RCS in ~/.zshenv
if [ -f /etc/zshrc ]; then source /etc/zshrc; fi
if [ -f /etc/zsh/zshrc ]; then source /etc/zsh/zshrc; fi


# To profile zsh startup, use the following:
# In ~/.zshrc,
#  (BEGIN) zmodload zsh/zprof
#  (END)   zprof >! ~/.zsh.startup.log
# % repeat 3 {time zsh -i -c exit}


# Default prompt host color for pure theme and tmux statusbar.
# You may want to have different color per machine (use ANSI color name or xterm color codes [0-255]).
#   - https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg
# The PROMPT_HOST_COLOR variable can be inherited from a parent shell, tmux, or SSH session.
if [[ -z "$PROMPT_HOST_COLOR" ]]; then
  export PROMPT_HOST_COLOR="6"  # cyan
fi

# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# Even if .zshrc fails to load powerlevel10k, do not enter the configuration wizard; just show errors!
export POWERLEVEL9K_DISABLE_CONFIGURATION_WIZARD=true

# autoload built-in zsh utilities.
autoload -Uz is-at-least
autoload -Uz colors && colors


# Source antidote
if [[ ! -s "${ZDOTDIR:-$HOME}/.zsh/antidote/antidote.zsh" ]]; then
  echo -e "\033[0;31m antidote is not installed; please update dotfiles !"
  echo -e "\033[0;33m  Try one of the following: \
       $ dotfiles update\n\
       $ cd ~/.dotfiles && python install.py\
       $ cd ~/.dotfiles && git submodule update --init --recursive\
"
  echo -e "\033[0m"
  return
fi
source "${ZDOTDIR:-$HOME}/.zsh/antidote/antidote.zsh"

# Source the Prezto configuration file.
if [[ -s "${ZDOTDIR:-$HOME}/.zpreztorc" ]]; then
  source "${ZDOTDIR:-$HOME}/.zpreztorc"
fi

# Do not put all usernames as possible candidates for tab completion.
zstyle ':completion:*' users root $USER


# virtualenvwrapper -- use lazy load (see prezto#669)
if (( $+commands[virtualenvwrapper_lazy.sh] )); then
    source "$commands[virtualenvwrapper_lazy.sh]"
fi

# nvm -- sourcing is very slow, use lazy load
if [[ -f "$HOME/.nvm/nvm.sh" ]]; then
  function nvm() {
    unfunction nvm
    source "$HOME/.nvm/nvm.sh"
    nvm "$@"
  }
fi

# Additional zplug from ~/.zshrc.local
if [[ -s "${ZDOTDIR:-$HOME}/.zshrc.local" ]]; then
  source "${ZDOTDIR:-$HOME}/.zshrc.local"
fi

# Misc plugin configs {{{
# -----------------------

# fzf-marks
export FZF_MARKS_JUMP='^g'

# }}}

# ------------------------------------------------------ }}}

# antidote: zsh plugin specifications.
# antidote-managed plugins will be stored at $ANTIDOTE_HOME
export ANTIDOTE_HOME="$HOME/.zsh/antidote-plugins"
export ANTIDOTE_BUNDLE="$HOME/.zsh/antidote.bundled.zsh"
zstyle ':antidote:bundle' use-friendly-names on

if [ ! -d "$ANTIDOTE_HOME" ]; then
    echo -e "\033[0;33mInitializing ANTIDOTE and zsh plugins for the first time, please be patient ...\033[0m"
fi

function antidote-load() {
    echo "antidote load is disabled. see ~/.zshrc"
    return 1;
}
function antidote-reset() {
    echo "Removing $ANTIDOTE_BUNDLE ..."
    rm -rf $ANTIDOTE_BUNDLE >/dev/null
}

# antidote: Use static loading (cache) for better performance
# (see antidote#65 for more details)
local -a bundles=()
local _ANTIDOTE_SAVING=""

function _antidote_compile_bundles() {
  echo -e "$fg[yellow]Writing antidote cache file into $ANTIDOTE_BUNDLE ...$reset_color"
  local PLUGINS_SPEC="$HOME/.zsh/plugins.zsh"

  # run $PLUGINS_SPEC and get the list of plugins line-by-line
  local -a bundles; bundles=("${(@f)$(zsh $PLUGINS_SPEC)}")

  if [ ! $? -eq 0 ]; then  # error
    echo -e "$fg[red]ERROR while generating plugin specs. Check $PLUGINS_SPEC.$reset_color"
    return 1;
  fi

  # list the plugins being loaded
  print -P -- "%F{243}$(printf "  - %s\n" $bundles)%f"

  ( set -o pipefail;
    echo "# Auto-generated by antidote and $PLUGINS_SPEC"
    printf "%s\n" $bundles | antidote bundle ) >! "$ANTIDOTE_BUNDLE"
}

# If $ANTIDOTE_BUNDLE is empty (blank) file, refresh the static cache
if [ ! -s "$ANTIDOTE_BUNDLE" ] || ! grep -q '[^[:space:]]' < "$ANTIDOTE_BUNDLE"; then
  _antidote_compile_bundles
fi

# Load the static script for loading zsh plugins.
source $ANTIDOTE_BUNDLE
if [ ! $? -eq 0 ] ; then   # error, refresh the script and try again
  echo -e "$fg[yellow]Sourcing ${ANTIDOTE_BUNDLE} has failed. Trying to reset zsh plugins ...$rest_color"
  _antidote_compile_bundles
  source $ANTIDOTE_BUNDLE
fi

if [[ -n "$_ANTIDOTE_SAVING" ]]; then
  # See fast-theme -i
  fast-theme "$HOME/.dotfiles/config/f-sy-h/wook.ini"
fi

# }}} ===================

# Fix inconsistent fpath order (workaround for antidote#157)
# system-wide zsh site-functions (/usr/local/share/zsh/, /opt/homebrew/share/zsh, etc.)
# should come AFTER local and antidote paths.
# some zsh magic: https://stackoverflow.com/questions/3435355/remove-entry-from-array
fpath_user=(${(@)fpath:#/(opt|usr)/*zsh*})   # remove all /opt, /usr path
fpath_system=(${(@)fpath:|fpath_user})       # $fpath \setminus $fpath_system
fpath=($fpath_user $fpath_system)

# fzf
(( ! ${path[(I)$HOME/.fzf/bin]} )) && path=( $HOME/.fzf/bin $path )
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh

# Manually source fzf-git.sh *after* fzf
# because sourcing it via plugin manager will make shell terminate
if type antidote >/dev/null 2>&1; then
  source $(antidote-path "junegunn/fzf-git.sh")/fzf-git.sh
  bindkey '^g^o' fzf-git-hashes-widget
  bindkey '^go' fzf-git-hashes-widget

else
  # old systems (e.g. Ubuntu 16.04) has low zsh version < 5.4
  # where antidote doesn't load. Fallback to zgen if possible
  echo -e "\033[0;31mERROR: antidote cannot load (your zsh is too old).\033[0m"
  [[ -f ~/.zgen/init.zsh ]] && { echo "Falling back to zgen..."; source ~/.zgen/init.zsh } || return 0;
fi


# Source zsh script files after loading the zsh plugins.
for config_file (${ZDOTDIR:-$HOME}/.zsh/zsh.d/*.zsh(N)) source $config_file

# Terminal
# Use xterm-256color (for tmux, too)
if [[ $TERM != "xterm-kitty" ]]; then
  export TERM="xterm-256color"
fi

# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.zsh/p10k.zsh ]] || source ~/.zsh/p10k.zsh


# iTerm integration (for OS X iTerm2)
# @see https://iterm2.com/shell_integration.html
if [[ "`uname`" == "Darwin" ]] && [[ -f ${HOME}/.iterm2_shell_integration.zsh ]]; then
    source ${HOME}/.iterm2_shell_integration.zsh
fi

if (( $+commands[iterm-tab-color] )); then
    # set tab color, if it is a new connection to remote through SSH
    function iterm_tab_color_auto() {
        if [ -z "$TMUX" ] && [ -n "$SSH_CONNECTION" ] && [ -n "$PROMPT_HOST_COLOR" ]; then
            iterm-tab-color $PROMPT_HOST_COLOR
        fi
    }
    iterm_tab_color_auto
fi

# Anaconda3
# see ~/.zshenv for $CONDA_EXE detection
function _conda_initialize() {
# >>> conda initialize >>>
if [ -n "${CONDA_EXE}" ]; then
  ${CONDA_EXE} config --set auto_activate_base false
  __conda_setup="$(${CONDA_EXE} 'shell.zsh' 'hook' 2> /dev/null)"
  if [ $? -eq 0 ]; then
      eval "$__conda_setup"
  fi
  unset __conda_setup
fi
# <<< conda initialize <<<
}
# Note: conda initialize is slow (0.3 sec), so execute lazily
conda() {
  unfunction conda
  _conda_initialize
  conda "$@"
}

if [[ -z "$CONDA_EXE" && -d "/opt/homebrew/Caskroom/miniconda" ]]; then
  echo "Warning: Please install miniconda locally on your HOME, not via Homebrew."
  echo "$ wget https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh"
  echo "$ ./Miniconda3-latest-MacOSX-x86_64.sh -p $HOME/.miniconda3"
fi

# Optionally, put local startup config (not version controlled) in ~/.zshrc.local
if [ -f "$HOME/.zshrc.local" ]; then
    source "$HOME/.zshrc.local"
fi


# vim: set ts=2 sts=2 sw=2:
